<template>
  <view class="user-center-page">
    <!-- 顶部背景装饰 -->
    <view class="header-bg">
      <view class="bg-decoration"></view>
    </view>

    <!-- 用户信息卡片 -->
    <view class="user-card">
      <view class="user-avatar-section">
        <view class="avatar-wrapper" @click="goToEditProfile">
          <image 
            :src="userInfo.avatar" 
            class="user-avatar" 
            mode="aspectFill"
          />
          <view class="avatar-edit-btn">
            <u-icon name="camera" size="24" color="#fff" />
          </view>
        </view>
        <view class="user-details">
          <text class="user-name">{{ userInfo.nickname || '点击登录' }}</text>
          <view class="user-tags">
            <text class="vip-tag">{{ userInfo.level || '普通会员' }}</text>
            <text class="points-tag">积分: {{ userInfo.points || 0 }}</text>
          </view>
        </view>
      </view>
      
      <!-- 用户数据统计 -->
      <view class="user-stats">
        <view class="stat-item" @click="goToOrders">
          <text class="stat-number">{{ userStats.orderCount }}</text>
          <text class="stat-label">订单数</text>
        </view>
        <view class="stat-divider"></view>
        <view class="stat-item" @click="goToWallet">
          <text class="stat-number">¥{{ userStats.balance }}</text>
          <text class="stat-label">余额</text>
          <!-- 调试信息 -->
          <!-- <text class="debug-info" style="font-size: 20rpx; color: #999;">{{ JSON.stringify(userStats) }}</text> -->
        </view>
      </view>
    </view>

    <!-- 快捷功能区 -->
    <view class="quick-actions">
      <view class="section-title">
        <text class="title-text">快捷功能</text>
      </view>
      <view class="action-grid">
        <view class="action-item" @click="goToOrders">
          <view class="action-icon order-icon">
            <u-icon name="list" size="48" color="#fff" />
          </view>
          <text class="action-label">我的订单</text>
        </view>
        
        <view class="action-item" @click="goToWallet">
          <view class="action-icon wallet-icon">
            <u-icon name="rmb" size="48" color="#fff" />
          </view>
          <text class="action-label">钱包充值</text>
        </view>
        
        <view class="action-item" @click="goToVIP">
          <view class="action-icon vip-icon">
            <u-icon name="star" size="48" color="#fff" />
          </view>
          <text class="action-label">会员中心</text>
        </view>
        
        <view class="action-item" @click="goToAIService">
          <view class="action-icon ai-icon">
            <u-icon name="chat" size="48" color="#fff" />
          </view>
          <text class="action-label">AI客服</text>
        </view>
      </view>
    </view>

    <!-- 服务列表 -->
    <view class="service-list">
      <view class="section-title">
        <text class="title-text">更多服务</text>
      </view>
      
      <view class="service-item" @click="goToFeedback">
        <view class="service-left">
          <view class="service-icon feedback-icon">
            <u-icon name="edit-pen" size="40" color="#FF6B6B" />
          </view>
          <text class="service-name">意见反馈</text>
        </view>
        <u-icon name="arrow-right" size="32" color="#ccc" />
      </view>
      
      <view class="service-item" @click="goToSettings">
        <view class="service-left">
          <view class="service-icon settings-icon">
            <u-icon name="setting" size="40" color="#4FACFE" />
          </view>
          <text class="service-name">设置</text>
        </view>
        <u-icon name="arrow-right" size="32" color="#ccc" />
      </view>
      
      <view class="service-item" @click="goToAbout">
        <view class="service-left">
          <view class="service-icon about-icon">
            <u-icon name="info-circle" size="40" color="#07C160" />
          </view>
          <text class="service-name">关于我们</text>
        </view>
        <u-icon name="arrow-right" size="32" color="#ccc" />
      </view>
    </view>

    <!-- 底部安全区域 -->
    <view class="safe-area-bottom"></view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { getUserStats } from '@/api/order.js'

// 用户信息
const userInfo = ref({
  avatar: '/static/default.png',
  nickname: '微信用户',
  level: '普通会员',
  points: 0
})

// 用户统计数据
const userStats = ref({
  orderCount: 0,
  balance: '0.00'
})

onMounted(() => {
  loadUserInfo()
  loadUserStats()
  
  // 监听用户数据更新事件
  uni.$on('userStatsUpdated', () => {
    console.log('接收到用户数据更新事件，重新加载统计数据')
    loadUserStats()
  })
})

// 页面卸载时清理事件监听
onUnmounted(() => {
  uni.$off('userStatsUpdated')
})

// uni-app页面生命周期 - 页面显示时触发
const onShow = () => {
  console.log('个人中心页面显示，重新加载数据')
  loadUserStats()
}

// 导出页面生命周期给uni-app使用
defineExpose({
  onShow
})

// 加载用户信息
function loadUserInfo() {
  const cachedUserInfo = uni.getStorageSync('userInfo')
  if (cachedUserInfo) {
    userInfo.value = {
      ...userInfo.value,
      ...cachedUserInfo
    }
  }
}

// 加载用户统计数据
async function loadUserStats() {
  try {
    // 获取当前用户ID，优先从缓存获取，否则使用默认值
    const cachedUserId = uni.getStorageSync('userId')
    const cachedUserInfo = uni.getStorageSync('userInfo')
    const userId = cachedUserId || cachedUserInfo?.id
    
    console.log('个人中心 - 开始加载用户统计数据')
    console.log('个人中心 - 缓存的userId:', cachedUserId, '类型:', typeof cachedUserId)
    console.log('个人中心 - 缓存的userInfo:', cachedUserInfo)
    console.log('个人中心 - 最终使用的userId:', userId, '类型:', typeof userId)
    
    if (!userId) {
      console.warn('个人中心 - 未找到用户ID，无法获取统计数据')
      uni.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 2000
      })
      return
    }
    
    console.log('个人中心 - 准备调用getUserStats API，userId:', userId)
    
    const response = await getUserStats(userId)
    console.log('个人中心 - 用户统计API原始响应:', response)
    console.log('个人中心 - API响应类型:', typeof response)
    console.log('个人中心 - API响应结构:', JSON.stringify(response, null, 2))
    
    // 根据后端实际返回的数据格式处理
    // 当code=200时，request.js返回res.data.data
    // 当code!=200时，request.js返回完整的res.data
    console.log('个人中心 - 分析响应数据结构')
    
    // 检查是否是成功的响应（直接返回的data）
    if (response && typeof response === 'object' && (response.orderCount !== undefined || response.balance !== undefined)) {
      // 这是成功的响应，response就是后端返回的stats数据
      console.log('个人中心 - 识别为成功响应，直接数据格式')
      console.log('个人中心 - response.orderCount:', response.orderCount)
      console.log('个人中心 - response.balance:', response.balance)
      
      const newStats = {
        orderCount: response.orderCount || 0,
        balance: response.balance || '0.00'
      }
      console.log('个人中心 - 准备更新用户统计数据:', newStats)
      console.log('个人中心 - 当前用户统计数据:', userStats.value)
      
      userStats.value = newStats
      
      console.log('个人中心 - 用户统计数据更新后:', userStats.value)
      
    } else if (response && response.code && response.data) {
      // 这是完整的响应格式（可能是错误响应）
      console.log('个人中心 - 识别为完整响应格式')
      console.log('个人中心 - response.code:', response.code)
      console.log('个人中心 - response.data:', response.data)
      
      if (response.code === 200) {
        const newStats = {
          orderCount: response.data.orderCount || 0,
          balance: response.data.balance || '0.00'
        }
        userStats.value = newStats
      } else {
        console.warn('个人中心 - API返回错误，code:', response.code)
        userStats.value = {
          orderCount: 0,
          balance: '0.00'
        }
      }
    } else {
      console.warn('个人中心 - 无法识别的响应格式，使用默认值')
      console.log('个人中心 - 完整response:', response)
      
      // 使用默认值
      userStats.value = {
        orderCount: 0,
        balance: '0.00'
      }
    }
  } catch (error) {
    console.error('获取用户统计数据出错:', error)
    // 出错时使用默认值
    userStats.value = {
      orderCount: 0,
      balance: '0.00'
    }
    
    uni.showToast({
      title: '获取数据失败',
      icon: 'none',
      duration: 2000
    })
  }
}

// 跳转到编辑资料页面
function goToEditProfile() {
  uni.showModal({
    title: '编辑资料',
    content: '编辑资料功能开发中...',
    showCancel: false
  })
}

// 跳转到订单页面
function goToOrders() {
  uni.navigateTo({
    url: '/pages/order/order'
  })
}

// 跳转到钱包页面
function goToWallet() {
  uni.navigateTo({
    url: '/pages/wallet/wallet'
  })
}

// 跳转到VIP页面
function goToVIP() {
  uni.navigateTo({
    url: '/pages/VIP/VIP'
  })
}

// 跳转到AI客服页面
function goToAIService() {
  uni.navigateTo({
    url: '/pages/AIService/AIService'
  })
}

// 意见反馈
function goToFeedback() {
  uni.showModal({
    title: '意见反馈',
    content: '感谢您的反馈！我们会持续改进产品体验。',
    showCancel: false
  })
}

// 设置页面
function goToSettings() {
  uni.showModal({
    title: '设置',
    content: '设置功能开发中...',
    showCancel: false
  })
}

// 关于我们
function goToAbout() {
  uni.showModal({
    title: '关于我们',
    content: '智慧餐饮系统 v1.0\n为您提供便捷的用餐体验',
    showCancel: false
  })
}
</script>

<style scoped>
.user-center-page {
  min-height: 100vh;
  background: linear-gradient(180deg, #f8faff 0%, #ffffff 100%);
  position: relative;
}

/* 顶部背景装饰 */
.header-bg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 400rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 0 0 60rpx 60rpx;
  overflow: hidden;
}

.bg-decoration {
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
  animation: float 8s ease-in-out infinite;
}

@keyframes float {
  0%, 100% { transform: translate(-50%, -50%) rotate(0deg); }
  50% { transform: translate(-50%, -50%) rotate(180deg); }
}

/* 用户信息卡片 */
.user-card {
  position: relative;
  margin: 60rpx 30rpx 30rpx;
  background: #ffffff;
  border-radius: 24rpx;
  padding: 40rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
  z-index: 2;
}

.user-avatar-section {
  display: flex;
  align-items: center;
  margin-bottom: 40rpx;
}

.avatar-wrapper {
  position: relative;
  margin-right: 30rpx;
}

.user-avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  border: 4rpx solid rgba(102, 126, 234, 0.2);
}

.avatar-edit-btn {
  position: absolute;
  bottom: -8rpx;
  right: -8rpx;
  width: 48rpx;
  height: 48rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.4);
}

.user-details {
  flex: 1;
}

.user-name {
  font-size: 36rpx;
  font-weight: bold;
  color: #1a1a1a;
  margin-bottom: 16rpx;
}

.user-tags {
  display: flex;
  gap: 16rpx;
}

.vip-tag {
  background: linear-gradient(135deg, #FFD700 0%, #FFA500 100%);
  color: #ffffff;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 22rpx;
  font-weight: 600;
}

.points-tag {
  background: rgba(102, 126, 234, 0.1);
  color: #667eea;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 22rpx;
  font-weight: 600;
}

/* 用户统计 */
.user-stats {
  display: flex;
  align-items: center;
  justify-content: space-around;
  padding: 30rpx 0;
  background: #f8f9ff;
  border-radius: 16rpx;
  gap: 40rpx;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
}

.stat-number {
  font-size: 32rpx;
  font-weight: bold;
  color: #667eea;
  margin-bottom: 8rpx;
}

.stat-label {
  font-size: 24rpx;
  color: #666666;
}

.stat-divider {
  width: 2rpx;
  height: 60rpx;
  background: #e8eaff;
}

/* 快捷功能区 */
.quick-actions {
  margin: 0 30rpx 30rpx;
}

.section-title {
  margin-bottom: 30rpx;
}

.title-text {
  font-size: 32rpx;
  font-weight: bold;
  color: #1a1a1a;
}

.action-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 30rpx;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 30rpx 20rpx;
  background: #ffffff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.action-item:active {
  transform: scale(0.95);
}

.action-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20rpx;
}

.order-icon { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
.wallet-icon { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
.vip-icon { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
.ai-icon { background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); }

.action-label {
  font-size: 24rpx;
  color: #666666;
  text-align: center;
}

/* 服务列表 */
.service-list {
  margin: 0 30rpx;
  background: #ffffff;
  border-radius: 20rpx;
  padding: 40rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
}

.service-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 0;
  border-bottom: 2rpx solid #f5f5f5;
}

.service-item:last-child {
  border-bottom: none;
}

.service-left {
  display: flex;
  align-items: center;
}

.service-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 24rpx;
}

.feedback-icon { background: rgba(255, 107, 107, 0.1); }
.settings-icon { background: rgba(79, 172, 254, 0.1); }
.about-icon { background: rgba(7, 193, 96, 0.1); }

.service-name {
  font-size: 30rpx;
  color: #1a1a1a;
  font-weight: 500;
}

/* 底部安全区域 */
.safe-area-bottom {
  height: 60rpx;
}
</style>